;(function(){
	bf_service_create = function(serviceInstance, request){
		var fields = [], values = [];
		var pojo = serviceInstance.pojo;
		
		for(var field in pojo){
			var value = request.getParameter(field);
			if (canWrite(value)){
				fields.push('`' + field + '`');
				var fieldObj = pojo[field];
				value = getJSType(fieldObj, value);
				fieldObj.value = value; // 写入 java 字段对象
										// 这样获取 System.out.println("this.pojo.name.value:"+getPojo().name.value);
				value = json2sql(value);
				
//				println(field + '=======' + value);
//				if(value && typeof value == 'string')value =trim(value);
				values.push(value);
			}
		}
		
		var now = json2sql(new Date);

		fields.push('createDate', 'updateDate');
		values.push(now, now);
		
		return "INSERT INTO {tableName} ({columns}) VALUES ({values})".format({
			tableName : serviceInstance.getTableName(),
			columns : fields.join(', '),
			values : values.join(', ')
		});
	}
	
	var jsType = {
		String : String,
		Number:Number,
		Boolean:Boolean,
		Date:String
	};
	
	/**
	 * 从 POJO 身上获取这个字段在 js 中是什么类型的
	 */
	function getJSType(fieldObj, rawValue, field){
		if(!fieldObj || !fieldObj.jsType)return undefined;
		
		var fn = jsType[fieldObj.jsType];
		
		if(!fn)throw 'No spec. jsType!' + field;
		
		if(fn === Boolean){ // boolean 要特定的转换
			if(rawValue == 1 || rawValue == 0){
				return rawValue == 1;
			}else{
				return fn(rawValue);
			}
		}
		
		return fn(rawValue);
	}
	
	function canWrite(value){
		// js !value stops 0 false
		if(value == '' || typeof value == 'function')return false;
		if(value == undefined)return false;
		if(value == null)return false;
		
		return true;
	}
	
	bf_service_update = function (serviceInstance, request, id, isPut){
		var pojo = serviceInstance.pojo;
		var params = isPut ? fixPut(request) : request;
		var pairs = [];
		
		for(var field in pojo){
			// 可从两处地方注入 value，一个是 Request hash，另外一个是 getXXX() 有返回值。getXXX() 有较高优先级
			var value = isPut ? params[field] : params.getParameter(field);
			if(field == "updateDate" && !value){
				// 未指定更新日期，自动添加
				pairs.push('updateDate = ' + json2sql(new Date));
			}else if (canWrite(value)){ // 有字符串的才写
				var fieldObj = pojo[field];
				value = getJSType(fieldObj, value, field);
				fieldObj.value = value; // 写入 java 字段对象
				// 这样获取 System.out.println("this.pojo.name.value:"+getPojo().name.value);
				
	//			if(value == String(Number(value))) value = Number(v);
				
				value = json2sql(value);
				//println(field + '=======' + value);
				pairs.push(field + ' = ' +value);
			}
		}
		
		println('serviceInstance:::::::' + serviceInstance.getTableName());
		var sql = "UPDATE {tableName} SET {pairs} WHERE id = {id}".format({
			tableName : serviceInstance.getTableName(),
			pairs : pairs.join(', '),
			id : id || getId() || (isPut ? params.id : params.getParameter('id'))
		});
		
		println('sql::::::' + sql);
		return sql;
	}
	
//	bf_service_update = function(serviceInstance, request, id){
//		return doUpdate(serviceInstance, request, id, true);
//	}
//	
//	bf_service_update_post = function(serviceInstance, request, id){
//		return doUpdate(serviceInstance, request, id);
//	}
	
	function getId(){
		var id = request.getParameter('id');
		if(!id)throw "no id!";
		return id;
	}
	
	function fixPut(request){
		var params = Packages.ajaxjs.net.Request.getPutRequest(request);
		params = String(params);
		var hash = {}, arr = params.split('&');
		for(var i = 0, j = arr.length; i < j; i++){
//			var kv = arr[i].split(/=.?/);
//			hash[kv.shift()] = kv.pop(); 
			
			var str = arr[i], index = str.indexOf('=');
			var key = str.substr(0, index), value = str.substr(index + 1);
			
			println(key + ':::' + value);
			
			hash[key] = decodeURIComponent(value); 
		}

		return hash;
	}
	
	
	/**
	 * 输入 JavaScript 数据类型，返回 SQL 的类型。
	 * @private
	 * @param {Mixed}
	 * @return {Mixed}
	 */
	function json2sql (val){
		if(typeof val == 'boolean'){
			return val === true ? 1 : 0;
		}else if(typeof val == 'number'){
			return Number(val);
		}else if(typeof val == 'string'){
			return "'" + zhuanyi(val) + "'";
		}else if(val.constructor == Date){
			return "'" + val.format('y-MM-dd hh:mm:ss') + "'";
		}else{
			return null;
		}
	};
	
	var all_qu = /'/g
	function zhuanyi(keyWord){
		keyWord = keyWord.replace(all_qu, "''");  
		
	//	keyWord = keyWord.replace("[", "/[");  
	//	keyWord = keyWord.replace("]", "/]");  
	//	keyWord = keyWord.replace("%", "/%");  
	//	keyWord = keyWord.replace("&","'/\&");  
	//	keyWord = keyWord.replace("_", "/_");  
	//	keyWord = keyWord.replace("(", "/(");  
	//	keyWord = keyWord.replace(")", "/)"); 
	//	keyWord = keyWord.replace("<", "/<"); 
	//	keyWord = keyWord.replace("=", "'="); 
		if(keyWord.indexOf('&')!= -1)println(':::::::::::'+keyWord);
		return keyWord;
	}
})();

